<template>
  <el-dialog
    v-model="visible"
    :title="`客户 ${customerName} 的合同`"
    width="80%"
    @close="handleClose"
  >
    <div class="customer-contracts-dialog">
      <!-- 合同统计 -->
      <div class="contract-stats">
        <el-card class="stat-card" shadow="never">
          <div class="stat-item">
            <div class="stat-label">合同总数</div>
            <div class="stat-value">{{ contractStats.total }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">合同金额</div>
            <div class="stat-value">{{ formatCurrency(contractStats.totalAmount) }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">最近合同</div>
            <div class="stat-value">{{ contractStats.lastContractDate || '无' }}</div>
          </div>
        </el-card>
      </div>

      <!-- 合同列表 -->
      <div class="contracts-list">
        <el-table
          :data="contracts"
          v-loading="loading"
          stripe
          style="width: 100%"
        >
          <el-table-column prop="contractNumber" label="合同编号" width="180">
            <template #default="{ row }">
              <span class="contract-number">{{ row.contractNumber }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="contractAmount" label="合同金额" width="120" align="right">
            <template #default="{ row }">
              <span class="amount">{{ formatCurrency(row.contractAmount) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="startDate" label="开始日期" width="120">
            <template #default="{ row }">
              {{ formatDate(row.startDate) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="endDate" label="结束日期" width="120">
            <template #default="{ row }">
              {{ formatDate(row.endDate) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="合同状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getContractStatusType(row.status)">
                {{ getContractStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="responsiblePerson" label="负责人" width="100">
            <template #default="{ row }">
              {{ row.responsiblePerson || '未分配' }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button type="primary" link @click="viewContractDetail(row)">
                查看详情
              </el-button>
              <el-button type="primary" link @click="editContract(row)">
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleAddContract">新增合同</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 合同详情对话框 -->
  <el-dialog
    v-model="contractDetailVisible"
    title="合同详情"
    width="800px"
    class="contract-detail-dialog"
  >
    <div class="contract-detail" v-if="selectedContract">
      <el-descriptions :column="2" border class="detail-descriptions">
        <el-descriptions-item label="合同编号" :span="2">
          {{ selectedContract.contractNumber }}
        </el-descriptions-item>
        <el-descriptions-item label="合同名称" :span="2">
          {{ selectedContract.contractName }}
        </el-descriptions-item>
        <el-descriptions-item label="合同金额">
          {{ formatCurrency(selectedContract.contractAmount) }}
        </el-descriptions-item>
        <el-descriptions-item label="开始日期">
          {{ formatDate(selectedContract.startDate) }}
        </el-descriptions-item>
        <el-descriptions-item label="结束日期">
          {{ formatDate(selectedContract.endDate) }}
        </el-descriptions-item>
        <el-descriptions-item label="合同状态">
          <el-tag :type="getContractStatusType(selectedContract.status)" class="status-tag">
            {{ getContractStatusText(selectedContract.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="负责人">
          {{ selectedContract.responsiblePerson || '未分配' }}
        </el-descriptions-item>
        <el-descriptions-item label="签署日期">
          {{ formatDate(selectedContract.signDate) }}
        </el-descriptions-item>
        <el-descriptions-item label="客户联系人">
          {{ selectedContract.customerContact }}
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">
          {{ selectedContract.contactPhone }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ selectedContract.remark || '无' }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="contractDetailVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 新增/编辑合同对话框 -->
  <el-dialog
    v-model="contractFormVisible"
    :title="editingContract ? '编辑合同' : '新增合同'"
    width="600px"
    class="contract-form-dialog"
  >
    <el-form
      ref="contractFormRef"
      :model="contractForm"
      :rules="contractFormRules"
      label-width="100px"
    >
      <el-form-item label="合同编号" prop="contractNumber">
        <el-input v-model="contractForm.contractNumber" />
      </el-form-item>
      
      <el-form-item label="合同名称" prop="contractName">
        <el-input v-model="contractForm.contractName" />
      </el-form-item>
      
      <el-form-item label="合同金额" prop="contractAmount">
        <el-input-number 
          v-model="contractForm.contractAmount" 
          :min="0" 
          controls-position="right" 
          style="width: 100%"
        />
      </el-form-item>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker
              v-model="contractForm.startDate"
              type="date"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker
              v-model="contractForm.endDate"
              type="date"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="合同状态" prop="status">
        <el-select v-model="contractForm.status" style="width: 100%">
          <el-option label="待签署" value="pending" />
          <el-option label="已签署" value="signed" />
          <el-option label="执行中" value="executing" />
          <el-option label="已完成" value="completed" />
          <el-option label="已终止" value="terminated" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="负责人" prop="responsiblePerson">
        <el-input v-model="contractForm.responsiblePerson" />
      </el-form-item>
      
      <el-form-item label="客户联系人" prop="customerContact">
        <el-input v-model="contractForm.customerContact" />
      </el-form-item>
      
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="contractForm.contactPhone" />
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input 
          v-model="contractForm.remark" 
          type="textarea" 
          :rows="3"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="contractFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveContract">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import { customerAPI } from '@/api/customer'

interface Contract {
  id: number
  contractNumber: string
  contractName: string
  contractAmount: number
  startDate: string
  endDate: string
  status: string
  responsiblePerson: string | null
  customerContact: string
  contactPhone: string
  signDate: string
  remark: string | null
}

interface Props {
  modelValue: boolean
  customerId: string
  customerName: string
}

interface ContractStats {
  total: number
  totalAmount: number
  lastContractDate: string | null
}

const props = defineProps<Props>()
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
}>()

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const contracts = ref<Contract[]>([])
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const contractStats = ref<ContractStats>({
  total: 0,
  totalAmount: 0,
  lastContractDate: null
})

// 合同详情相关状态
const contractDetailVisible = ref(false)
const selectedContract = ref<Contract | null>(null)

// 合同表单相关状态
const contractFormVisible = ref(false)
const contractFormRef = ref<FormInstance>()
const editingContract = ref<Contract | null>(null)

const contractForm = ref({
  contractNumber: '',
  contractName: '',
  contractAmount: 0,
  startDate: '',
  endDate: '',
  status: 'pending',
  responsiblePerson: '',
  customerContact: '',
  contactPhone: '',
  signDate: '',
  remark: ''
})

const contractFormRules = ref<FormRules>({
  contractNumber: [
    { required: true, message: '请输入合同编号', trigger: 'blur' }
  ],
  contractName: [
    { required: true, message: '请输入合同名称', trigger: 'blur' }
  ],
  contractAmount: [
    { required: true, message: '请输入合同金额', trigger: 'blur' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' }
  ]
})

// 监听modelValue变化
watch(
  () => props.modelValue,
  (newValue: boolean) => {
    visible.value = newValue
    if (newValue) {
      loadContracts()
    }
  }
)

// 监听visible变化
watch(visible, (newValue: boolean) => {
  emit('update:modelValue', newValue)
})

// 格式化货币
const formatCurrency = (amount: number): string => {
  // 确保金额是数字类型
  const numericAmount = typeof amount === 'string' ? parseFloat(amount) : amount
  if (isNaN(numericAmount)) return '¥0.00'
  
  return '¥' + numericAmount.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
}

// 格式化日期
const formatDate = (date: string): string => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

// 合同状态文本
const getContractStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    pending: '待签署',
    signed: '已签署',
    executing: '执行中',
    completed: '已完成',
    terminated: '已终止'
  }
  return statusMap[status] || status
}

// 合同状态类型
const getContractStatusType = (status: string): string => {
  const typeMap: Record<string, string> = {
    pending: 'warning',
    signed: 'primary',
    executing: 'info',
    completed: 'success',
    terminated: 'danger'
  }
  return typeMap[status] || 'info'
}

// 加载合同数据
const loadContracts = async (): Promise<void> => {
  if (!props.customerId) return
  
  loading.value = true
  try {
    const response: any = await customerAPI.getCustomerContracts(props.customerId, {
      page: pagination.value.currentPage,
      limit: pagination.value.pageSize
    })
    
    // 映射后端返回的数据字段
    contracts.value = response.data.list.map((contract: any) => ({
      id: contract.id,
      contractNumber: contract.contractNumber,
      contractName: contract.contractName,
      contractAmount: parseFloat(contract.contractAmount),
      startDate: contract.startDate,
      endDate: contract.endDate,
      status: contract.status,
      responsiblePerson: contract.responsiblePerson,
      customerContact: contract.customerContact,
      contactPhone: contract.contactPhone,
      signDate: contract.signDate,
      remark: contract.remark
    }))
    
    pagination.value.total = response.data.pagination.total
    
    // 计算统计信息
    contractStats.value.total = response.data.pagination.total
    contractStats.value.totalAmount = contracts.value.reduce((sum: number, contract: Contract) => {
      const amount = typeof contract.contractAmount === 'string' ? parseFloat(contract.contractAmount) : contract.contractAmount
      return sum + (isNaN(amount) ? 0 : amount)
    }, 0)
    
    // 获取最近合同日期
    if (contracts.value.length > 0) {
      const sortedContracts = [...contracts.value].sort((a, b) => 
        new Date(b.startDate).getTime() - new Date(a.startDate).getTime()
      )
      contractStats.value.lastContractDate = formatDate(sortedContracts[0].startDate)
    }
  } catch (error) {
    console.error('加载合同失败:', error)
    ElMessage.error('加载合同失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (val: number): void => {
  pagination.value.pageSize = val
  pagination.value.currentPage = 1
  loadContracts()
}

// 处理当前页变化
const handleCurrentChange = (val: number): void => {
  pagination.value.currentPage = val
  loadContracts()
}

// 查看合同详情
const viewContractDetail = (contract: Contract): void => {
  selectedContract.value = contract
  contractDetailVisible.value = true
}

// 编辑合同
const editContract = (contract: Contract): void => {
  editingContract.value = contract
  contractForm.value = { ...contract }
  contractFormVisible.value = true
}

// 新增合同
const handleAddContract = (): void => {
  editingContract.value = null
  contractForm.value = {
    contractNumber: '',
    contractName: '',
    contractAmount: 0,
    startDate: '',
    endDate: '',
    status: 'pending',
    responsiblePerson: '',
    customerContact: '',
    contactPhone: '',
    signDate: '',
    remark: ''
  }
  contractFormVisible.value = true
}

// 保存合同
const saveContract = async (): Promise<void> => {
  if (!contractFormRef.value) return
  
  await contractFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        let response: any
        if (editingContract.value) {
          // 编辑合同
          response = await customerAPI.updateCustomerContract(props.customerId, editingContract.value.id, contractForm.value)
          ElMessage.success('合同更新成功')
        } else {
          // 新增合同
          response = await customerAPI.createCustomerContract(props.customerId, contractForm.value)
          ElMessage.success('合同创建成功')
        }
        
        contractFormVisible.value = false
        loadContracts()
      } catch (error) {
        console.error('保存合同失败:', error)
        ElMessage.error('保存合同失败: ' + (error as Error).message)
      }
    }
  })
}

// 关闭对话框
const handleClose = (): void => {
  visible.value = false
  contracts.value = []
  pagination.value = {
    currentPage: 1,
    pageSize: 10,
    total: 0
  }
  contractStats.value = {
    total: 0,
    totalAmount: 0,
    lastContractDate: null
  }
}
</script>

<style scoped lang="scss">
.customer-contracts-dialog {
  .contract-stats {
    margin-bottom: 20px;
    
    .stat-card {
      .stat-item {
        display: inline-block;
        margin-right: 30px;
        
        .stat-label {
          font-size: 14px;
          color: #606266;
          margin-bottom: 5px;
        }
        
        .stat-value {
          font-size: 18px;
          font-weight: 600;
          color: #1f2d3d;
        }
      }
    }
  }
  
  .contracts-list {
    margin-bottom: 20px;
    
    .contract-number {
      font-family: 'Monaco', 'Consolas', monospace;
      font-size: 12px;
      color: #606266;
    }
    
    .amount {
      font-weight: 600;
      color: #f56c6c;
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.contract-detail-dialog {
  .contract-detail {
    padding: 20px 0;
  }
  
  .detail-descriptions {
    margin-bottom: 20px;
  }
}

.contract-form-dialog {
  .el-form {
    padding: 20px 0;
  }
}
</style>